<template>
  <view class="recharge-page">
    <view class="header">
      <view class="title">充值中心</view>
    </view>

    <view class="section">
      <view class="section-title">选择券类型</view>
      <view class="coupon-type-selector">
        <view
          class="coupon-type-item"
          :class="{ active: selectedCouponType === 'A' }"
          @tap="selectedCouponType = 'A'"
        >
          <text>A券</text>
        </view>
        <view
          class="coupon-type-item"
          :class="{ active: selectedCouponType === 'B' }"
          @tap="selectedCouponType = 'B'"
        >
          <text>B券</text>
        </view>
      </view>
    </view>

    <view class="section">
      <view class="section-title">充值金额</view>
      <view class="coupon-type-selector">
        <view
          class="coupon-type-item"
          v-for="item in amountList"
          :class="{ active: selectedCouponAmount === item.id }"
          :key="item.id"
          @tap="selectedCouponAmount = item.id"
        >
          <text>{{ item.amount }} （返{{ item.deduction }}）</text>
        </view>
      </view>

      <view class="quantity-selector">
        <view class="quantity-label">购买数量：</view>
        <view class="quantity-controls">
          <view
            class="quantity-btn decrease"
            :class="{ disabled: quantity <= 1 }"
            @tap="decreaseQuantity"
          >
            —
          </view>
          <input
            class="quantity-input"
            type="number"
            :value="quantity"
            @input="handleQuantityInput"
            @blur="validateQuantity"
          />
          <view
            class="quantity-btn increase"
            :class="{ disabled: quantity >= maxQuantity }"
            @tap="increaseQuantity"
          >
            +
          </view>
        </view>
      </view>

      <view class="quantity-selector">
        <view class="quantity-label">抵扣金额：</view>
        <view class="amount-input">
          <text class="currency">¥</text>
          <input
            class="input"
            type="digit"
            :value="amount"
            placeholder="请输入抵扣金额"
            @input="handleAmountInput"
            pattern="[0-9]*"
            inputmode="numeric"
            step="1"
            min="0"
            :maxlength="10"
          />
        </view>
      </view>
    </view>
    <view style="color: #999">可用抵扣额度：{{ info.deduction_balance }}</view>
    <view
      >实际支付金额：<text style="color: red">¥{{ payNum }}</text></view
    >

    <view class="submit-btn" @tap="handleSubmit">确定充值</view>
    <!-- <nut-textarea v-model="txt" /> -->
  </view>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from "vue";
import Taro from "@tarojs/taro";
import http from "@/utils/http";

import { store } from "@/store/index";
const { info, user, userType, token } = store.storeState;
const txt = ref(token.value);

// definePageConfig({
//   navigationBarTitleText: '充值',
// });

Taro.setNavigationBarTitle({
  title: "充值",
});

const payNum = computed(() => {
  console.log(
    "choseNum.value",
    choseNum.value,
    amount.value,
    "quantity",
    quantity.value
  );
  const totalAmount = choseNum.value * quantity.value;
  return (totalAmount - amount.value || 0).toFixed(2);
});

const amountList = computed(() => {
  return selectedCouponType.value == "A" ? amountListA.value : amountListB.value;
});

const choseNum = computed(() => {
  let total = 0;
  amountList.value.forEach((i) => {
    if (i.id == selectedCouponAmount.value) {
      total = i.amount;
    }
  });
  return total;
});

const amountListA = ref([]);
const amountListB = ref([]);

onMounted(() => {
  // 页面初始化时的逻辑
  http.post("/api/user/rechargeLevel?type=A").then((res: any) => {
    console.log("res", res);
    amountListA.value = res.data.map((i: any) => i.columns);
    selectedCouponAmount.value = amountList.value[0].id;
  });
  http.post("/api/user/rechargeLevel?type=B").then((res: any) => {
    console.log("res", res);
    amountListB.value = res.data.map((i: any) => i.columns);
    selectedCouponAmount.value = amountList.value[0].id;
  });
});

const selectedCouponType = ref("A");
const amount = ref(0);
const quantity = ref(1);
const maxQuantity = ref(99);

// 格式化显示的金额，确保只显示整数
const displayAmount = computed(() => {
  return Math.floor(amount.value) || 0;
});

// const amountList = ref([
//   { amount: 100.0, deduction: 80, id: "1" },
// ]);
const selectedCouponAmount = ref();

// 输入验证函数
const handleAmountInput = (e: any) => {
  let value = e.detail?.value || e.target?.value || "";

  // 只允许数字，移除所有非数字字符
  value = value.toString().replace(/[^\d.]/g, "");

  // 如果为空，设置为0
  if (value === "") {
    amount.value = 0;
    return;
  }

  // 转换为数字
  const numValue = parseFloat(value) || 0;

  // 获取最大限制值
  const maxDeduction = info.value.deduction_balance || 0;
  const maxPayNum = choseNum.value * quantity.value || 0;
  const maxAllowed = Math.min(maxDeduction, maxPayNum);

  // 限制最大值
  const finalValue = Math.min(numValue, maxAllowed);

  // 更新值
  amount.value = finalValue;

  // 如果输入超出限制，显示提示并设置为最大允许值
  if (numValue > maxAllowed && maxAllowed > 0) {
    Taro.showToast({
      title: `输入金额不能超过${maxAllowed}元`,
      icon: "none",
      duration: 1500,
    });
    // 直接设置为最大允许值，不需要延时
    amount.value = maxAllowed;
  }
};

// 数量控制函数
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

const increaseQuantity = () => {
  if (quantity.value < maxQuantity.value) {
    quantity.value++;
  }
};

const handleQuantityInput = (e: any) => {
  let value = parseInt(e.detail?.value || e.target?.value || "1");
  if (isNaN(value) || value < 1) {
    value = 1;
  }
  if (value > maxQuantity.value) {
    value = maxQuantity.value;
  }
  quantity.value = value;
};

const validateQuantity = () => {
  if (quantity.value < 1) {
    quantity.value = 1;
  }
  if (quantity.value > maxQuantity.value) {
    quantity.value = maxQuantity.value;
  }
};

const doPay = (param) => {
  Taro.requestPayment({
    timeStamp: param.timeStamp,
    nonceStr: param.nonceStr,
    package: param.prepayId,
    signType: param.signType,
    paySign: param.paySign,
    success: function (res) {
      console.log("支付 success", res);
      Taro.showToast({
        title: "支付成功",
        icon: "success",
      });
      Taro.navigateBack();
      // txt.value = JSON.stringify(res)
    },
    fail: function (res) {
      console.log("支付 fail", res);
      Taro.showToast({
        title: "支付失败",
        icon: "error",
      });
      txt.value = JSON.stringify(res);
    },
    complete: function (res) {
      console.log("支付 complete", res);
    },
  });
};

const handleSubmit = () => {
  // 验证输入
  if (amount.value < 0) {
    Taro.showToast({
      title: "请输入有效的充值金额",
      icon: "none",
    });
    return;
  }

  // 检查是否超过可用余额
  if (amount.value > info.value.deduction_balance) {
    Taro.showToast({
      title: "充值金额不能超过可用抵扣额度",
      icon: "none",
    });
    return;
  }

  // 检查是否超过实际支付金额
  // if (amount.value > Number(payNum.value)) {
  //   Taro.showToast({
  //     title: "充值金额不能超过实际支付金额",
  //     icon: "none",
  //   });
  //   return;
  // }

  const amountNum = Number(amount.value.toFixed(2));

  http
    .postQuery("/api/user/recharge", {
      id: selectedCouponAmount.value,
      deduction: amountNum,
      number: quantity.value,
    })
    .then((res: any) => {
      console.log("支付 === ", res);
      // pay(res.data.prepayId)

      if (res.data?.code == 1) {
        Taro.showToast({
          title: "支付成功",
          icon: "success",
        });
        return;
      }
      doPay(res.data);
    });

  /*
  Taro.showModal({
    title: "充值确认",
    content: `您选择了${
      selectedCouponType.value
    }券，充值金额为¥${amountNum.toFixed(2)}`,
    success: (res) => {
      if (res.confirm) {
        // 这里可以添加实际的充值API调用
        // Taro.showToast({
        //   title: "充值成功",
        //   icon: "success",
        //   duration: 2000,
        //   success: () => {
        //     setTimeout(() => {
        //       Taro.navigateBack();
        //     }, 2000);
        //   },
        // });

        // http
        //   .postQuery("/api/user/recharge", {
        //     id: selectedCouponAmount.value,
        //     deduction: amountNum,
        //   })
        //   .then((res) => {
        //     console.log("支付 === ", res);
        //     // pay(res.data.prepayId)
        //     doPay(res.data);
        //   });
      }
    },
  });
  */
};
</script>

<style lang="scss">
.recharge-page {
  min-height: 100vh;
  background-color: #f6f9ff;
  padding: 30rpx;

  .header {
    margin-bottom: 40rpx;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .section {
    background: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);

    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 30rpx;
    }

    .coupon-type-selector {
      display: flex;
      gap: 20rpx;

      .coupon-type-item {
        flex: 1;
        height: 80rpx;
        border-radius: 40rpx;
        border: 2rpx solid #ddd;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 28rpx;
        color: #666;

        &.active {
          background: hsl(17, 98%, 51%);
          color: #fff;
          border-color: hsl(17, 98%, 51%);
        }
      }
    }

    .quantity-selector {
      margin: 20rpx 0;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .quantity-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
      }

      .quantity-controls {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 20rpx;

        .quantity-btn {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
          background: #f5f5f5;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 32rpx;
          font-weight: bold;
          color: #333;

          &.decrease {
            background: #ff6b35;
            color: white;
          }

          &.increase {
            background: #ff6b35;
            color: white;
          }

          &.disabled {
            background: #ddd !important;
            color: #999 !important;
          }
        }

        .quantity-input {
          width: 120rpx;
          height: 60rpx;
          text-align: center;
          font-size: 28rpx;
          border: 2rpx solid #eee;
          border-radius: 8rpx;
          background: white;
        }
      }
    }

    .amount-input {
      display: flex;
      align-items: center;
      border-bottom: 2rpx solid #eee;
      padding-bottom: 20rpx;
      margin-top: 20rpx;

      .currency {
        font-size: 40rpx;
        font-weight: bold;
        color: #333;
        margin-right: 10rpx;
      }

      .input {
        flex: 1;
        font-size: 40rpx;
        height: 80rpx;
      }
    }
  }

  .submit-btn {
    height: 90rpx;
    border-radius: 45rpx;
    background: hsl(17, 98%, 51%);
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 32rpx;
    font-weight: bold;
    margin-top: 60rpx;
  }
}
</style>
